import type { DefaultOptionType } from "antd/es/select";
import { clsx, type ClassValue } from "clsx";
import NP from "number-precision";
import { twMerge } from "tailwind-merge";
import type { IDict } from "~/types/common";

/**
 * ui 相关的工具函数
 */

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/**
 * 提取 某一个 tree 中某一个字段的值
 */
export function collectKeys<T extends { children?: T[] }>(
  data: T[],
  field: keyof T,
): (string | number)[] {
  let arr: (string | number)[] = [];
  data.forEach((item) => {
    const value = item[field] as string | number;
    arr.push(value);
    if (item.children && item.children.length > 0) {
      arr = arr.concat(collectKeys(item.children, field));
    }
  });
  return arr;
}

/**
 * 构建并查集来存储节点的父节点信息
 */
export function buildUnionFind<T extends { id: number; children?: T[] }>(
  data: T[],
): Map<number, number> {
  const parentMap = new Map<number, number>();
  function traverse(node: T, parentId: number | null = null) {
    if (parentId !== null) {
      parentMap.set(node.id, parentId);
    }
    if (node.children) {
      node.children.forEach((child) => traverse(child, node.id));
    }
  }
  data.forEach((node) => traverse(node));
  return parentMap;
}

/**
 * 查找某一个树节点的所有父级 key
 */
export function findAllParentKeys<T extends { id: number; children?: T[] }>(
  data: T[],
  targetId: number,
): number[] {
  const parentMap = buildUnionFind(data);
  const parentKeys: number[] = [];
  let currentId: number = targetId;
  while (currentId && parentMap.has(currentId)) {
    const parentId = parentMap.get(currentId);
    if (parentId) {
      parentKeys.push(parentId);
      currentId = parentId;
    } else {
      break;
    }
  }
  return parentKeys;
}

/**
 * 查找某一个树节点的所有子集 key (递归查找)
 */
export function findAllChildKeys<T extends { id: number; children?: T[] }>(
  data: T[],
  targetId: number,
): number[] {
  const childKeys: number[] = [];

  function traverse(node: T) {
    if (node.id === targetId) {
      // 找到目标节点后，递归收集所有子节点
      collectChildren(node);
    } else if (node.children) {
      // 继续遍历子节点寻找目标节点
      node.children.forEach((child) => traverse(child));
    }
  }

  function collectChildren(node: T) {
    if (node.children) {
      node.children.forEach((child) => {
        childKeys.push(child.id);
        collectChildren(child); // 递归收集子节点的子节点
      });
    }
  }

  data.forEach((node) => traverse(node));
  return childKeys;
}

export function transTreeToAntdTreeData<
  T extends { id: number; children?: T[]; name?: string; label?: string },
>(tree: T[], parentName = "~"): any[] {
  return tree.map((item) => {
    // 拼接当前名称和父级名称
    const fullTitle = parentName
      ? `${parentName} / ${item.name || item.label}`
      : item.name || item.label;
    return {
      label: fullTitle,
      value: item.id,
      title: item.name || item.label,
      children: item.children
        ? transTreeToAntdTreeData(item.children, fullTitle)
        : undefined,
    };
  });
}

export function buildTree<
  T extends { id: number; children?: T[]; parentId?: number; sort?: number },
>(nodes: T[]): T[] {
  const nodeMap = new Map<number, T>();
  const tree: T[] = [];

  // 第一次遍历：构建映射表
  nodes.forEach((itemNode) => {
    nodeMap.set(itemNode.id, { ...itemNode });
  });

  // 第二次遍历：构建树结构
  nodes.forEach((itemNode) => {
    const node = nodeMap.get(itemNode.id);
    if (itemNode.parentId && itemNode.parentId > 0) {
      const parent = nodeMap.get(itemNode.parentId);
      if (parent) {
        if (!parent.children) {
          parent.children = [];
        }
        node && parent.children.push(node);
      }
    } else {
      node && tree.push(node);
    }
  });

  // 递归排序所有节点的children
  const sortChildren = (nodes: T[]) => {
    nodes.forEach((node) => {
      if (node.children) {
        node.children.sort((a, b) => (a.sort || 0) - (b.sort || 0));
        sortChildren(node.children);
      }
    });
    nodes.sort((a, b) => (a.sort || 0) - (b.sort || 0));
  };

  sortChildren(tree);
  return tree;
}

/**
 * dict 转 antd select options
 * @param dicts
 * @returns
 */
export function dictToOption(dicts: IDict[] = []): DefaultOptionType[] {
  const options: DefaultOptionType[] = [];
  const _handle = (dicts: IDict[]) => {
    for (const item of dicts) {
      options.push({
        label: item.label,
        value: item.code,
      });
    }
  };
  _handle(dicts || []);
  return options;
}

/**
 * 金额处理函数，分处理成元，保留两位小数
 */
export function amountToYuan(amount: number): number {
  if (!amount) {
    return 0;
  }
  return NP.round(amount / 100, 2);
}

/**
 * 金额处理函数，元处理成分
 */
export function amountToFen(amount: number): number {
  if (!amount) {
    return 0;
  }
  return NP.round(amount * 100, 2);
}

/**
 * 根据金额和税率计算扣税金额
 * 单位：分
 */
export function calculateTaxAmount(amount: number, taxRate: number): number {
  if (!amount || !taxRate) {
    return 0;
  }
  return NP.round((amount / (taxRate + 100)) * taxRate, 2);
}

/**
 * 校验章节标题是否合法，长度超过20肯定不是章节标题
 * @param line 章节标题
 * @returns
 */
export function isChapterTitle(line: string): boolean {
  const chapterTitleRegex =
    /^(第(?:\d+|[一二三四五六七八九十百千万]+)章(?:\s+.+)?|[A-Za-z]\.\s*\d+|(?:\d+|[一二三四五六七八九十]+)[.、]|\d+|[一二三四五六七八九十百千万]+)$/;
  return chapterTitleRegex.test(line.trim()) && line.trim().length < 20;
}

/**
 * 番外
 * @param line
 * @returns
 */
export function isChapterExtra(line: string): boolean {
  const chapterExtraRegex = /番外/g;
  return chapterExtraRegex.test(line.trim()) && line.trim().length < 20;
}


/**
 * 导语
 * @param line
 * @returns
 */
export function isChapterIntroduction(line: string): boolean {
  const chapterExtraRegex = /导语/g;
  return chapterExtraRegex.test(line.trim()) && line.trim().length < 20;
}



export function countWords(str: string): number {
  let sLen = 0;
  try {
    //先将回车换行符做特殊处理
    str = str.replace(/(\r\n+|\s+|　+)/g, "龘");
    //处理英文字符数字，连续字母、数字、英文符号视为一个单词
    str = str.replace(/[\x00-\xff]/g, "m");
    //合并字符m，连续字母、数字、英文符号视为一个单词
    str = str.replace(/m+/g, "*");
    //去掉回车换行符
    str = str.replace(/龘+/g, "");
    //返回字数
    sLen = str.length;
  } catch (e) {}
  return sLen;
}
